#pragma once

#include <iostream>
#include <string>
#include <sstream>
#include <sys/types.h>
#include <unistd.h>
#include <sys/stat.h>
#include "Util.hpp"

const std::string sep = "\r\n";
const std::string default_root = "./wwwroot";
const std::string home_page = "index.html";
const std::string html_404 = "wwwroot/404.html";

class HttpRequst
{
public:
    HttpRequst() {}
    ~HttpRequst() {}
    
    void parse()
    {
        // 1.从inbuffer中拿到第一行，分隔符\r\n
        std::string line = Util::getOneLine(inbuffer, sep);
        if (line.empty())
            return;
        
        // 2.从请求行提取三个字段
            //2.1 /aa.py?name=zhangsan&pwd=123
            //通过?将左右分离
            //post自动分离，get需要手动分离  
            //左边:PATH 右边parm 
        std::stringstream ss(line);
        ss >> method >> url >> httpversion;
        // 3.添加web默认路径
        path = default_root;              // ./wwwroot
        path += url;                      //./wwwroot/a.html
        if (path[path.size() - 1] == '/') // 默认路径
            path += home_page;

        // 4.获取path对应的后缀
        auto pos = path.rfind(".");
        if (pos == std::string::npos)
            suffix = ".html";
        else
            suffix = path.substr(pos);
        // 5.获取资源大小
        struct stat st;
        int n = stat(path.c_str(), &st);
        if (n == 0)
            size = st.st_size;
        else
            size = -1;
    }

public:
    std::string inbuffer;

    std::string method;      // 请求方式
    std::string url;         //
    std::string httpversion; // 版本号
    std::string path;        // 路径
    std::string suffix;      // 后缀

    int size;
};

class HttpResponse
{
public:
    std::string outbuffer;
};